package com.plugin.utils

import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

/**
 * 遍历 Object class，提取所有的 fields 转成 [fieldName: fieldValue] 并返回 Collection
 */
class FieldDelegate(private val clz: Class<*>) : ReadOnlyProperty<Any, Collection<String>> {
    lateinit var cache: Collection<String>
    override fun getValue(thisRef: Any, property: KProperty<*>): Collection<String> {
        if (this::cache.isInitialized) {
            return cache
        }
        val result = LinkedHashMap<String, String>()
        val fields = clz.declaredFields
        for (element in fields) {
            if (element.type.canonicalName == "java.lang.String") {
                element.let {
                    it.isAccessible = true
                    val filedName = it.name
                    val fieldValue = it.get(null).toString()
                    result[filedName] = fieldValue
                }
            }
        }
        cache = result.values
        return cache
    }
}